package com.item.utils;

import com.item.pojo.ScheduledFutureHolder;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

/**
 * 对定时任务动态控制的工具类
* @author likaiping
* @createTime 2024/5/14 15:04
*/
@Component
@AllArgsConstructor
public class ScheduledTaskUtil {

    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    //存储任务执行的包装类
    private HashMap<String , ScheduledFutureHolder> schedulerMap = new HashMap<>();

    /**
     * 启动任务
     * @return 结果
     */
    public String startTask(Runnable scheduledTask, String cron) {
        try {
            //初始化一个任务
//            ScheduledTask scheduledTask = new ScheduledTask();
//            String cron = "0/2 * * * *  ?";
            //把任务交给任务调度器执行
            ScheduledFuture<?> scheduledFuture = threadPoolTaskScheduler.schedule(scheduledTask,new CronTrigger(cron));

            //把任务包装成ScheduledFutureHolder
            ScheduledFutureHolder scheduledFutureHolder = new ScheduledFutureHolder();
            scheduledFutureHolder.setScheduledFuture(scheduledFuture);
            scheduledFutureHolder.setRunnableClass(scheduledTask.getClass());
            scheduledFutureHolder.setCron(cron);

            schedulerMap.put(scheduledFutureHolder.getRunnableClass().getName(), scheduledFutureHolder);
            return "启动任务成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "启动失败";
        }
    }

    /**
     * 查询所有任务
     */
    public HashMap<String,ScheduledFutureHolder> queryTask() {
        HashMap<String,ScheduledFutureHolder> map = new HashMap<>();
        schedulerMap.forEach((k,v)->{
            System.out.println("查询任务");
            System.out.println(k + "   " + v);
            map.put(k,v);
        });
        return map;
    }

    /**
     * 停止任务
     * @param className 类名
     */
    public String stopTask(String className) {
        //如果这个任务存在
        if (schedulerMap.containsKey(className)) {
            ScheduledFuture<?> scheduledFuture = schedulerMap.get(className).getScheduledFuture();
            //任务如果在执行
            if (scheduledFuture != null) {
                scheduledFuture.cancel(true);
                return "停止任务"+className+"成功";
            }
            return "任务"+className+"未在运行，无需停止";
        }
        return "任务不存在";
    }

    public String  restartTask(String className) throws InstantiationException, IllegalAccessException {
        //如果包含这个任务
        if (schedulerMap.containsKey(className)) {
            //cron可以通过前端传过来
            String cron = "0/50 * * * *  ?";
            ScheduledFutureHolder scheduledFutureHolder = schedulerMap.get(className);
            ScheduledFuture<?> scheduledFuture = scheduledFutureHolder.getScheduledFuture();
            if (scheduledFuture != null) {
                //如果不为空 先停掉任务
                scheduledFuture.cancel(true);

                //修改触发时间 重启任务
                Runnable runnable = scheduledFutureHolder.getRunnableClass().newInstance();

                //执行任务
                threadPoolTaskScheduler.schedule(runnable,new CronTrigger(cron));

                scheduledFutureHolder.setScheduledFuture(scheduledFuture);
                scheduledFutureHolder.setCron(cron);

                schedulerMap.put(scheduledFutureHolder.getRunnableClass().getName(),scheduledFutureHolder);
                return "重启任务"+className+"成功";
            }
            return "重启任务失败"+className+"任务未在运行";
        }
        return "任务不存在";
    }
}
